package com.neutech.filter;

import com.google.gson.Gson;
import com.neutech.entity.User;
import com.neutech.vo.ResultVO;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns = {"/cart/*","/order/*"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            PrintWriter out = servletResponse.getWriter();
            out.print(new Gson().toJson(ResultVO.error(3003,"未登录")));
            out.close();
        }
    }
}
